<?php

error_reporting(E_ALL & ~E_DEPRECATED);

function blacklist( $fileName ) {
	$blacklist = array(
		'svn',
		'nbproject',
		'idea',
		'cache/',
		'install/',
		'Thumbs.db',
		'phpseclib',
		'/install.php',
		'/check.php',
		'/sync.php',
		'.config.php',
		'.example.php',
		'skylive',
		'upload'
	);

	foreach( $blacklist as $pattern )
		if( strpos( $fileName, $pattern )) return true;
	return false;
}

$mode = empty( $argv[1] ) ? null : $argv[1];
$hashes = json_decode(file_get_contents('http://iv-cms.de/iv5/?interface=iv.listfiles'), true);
$iterate = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( '.' ));

set_include_path(get_include_path() . PATH_SEPARATOR . 'lib/phpseclib');

include 'inc/sftp.config.php';
include 'lib/phpseclib/Crypt/Blowfish.php';
include 'lib/phpseclib/Crypt/RSA.php';
include 'lib/phpseclib/Net/SFTP.php';

if($mode) {
	$sftp = new Net_SFTP('iv-cms.de');

	if (!$sftp->login($sftp_user, $sftp_pass)) {
		exit('Login Failed');
	}

	$sftp->chdir('/var/www/iv5/');
}

function upload( $fileName ) {
	global $sftp;

	$folders = explode( '/', $fileName );
	$dir = '.';

	while( count( $folders ) > 1 ) {
		$dir .= '/' . array_shift( $folders );
		$sftp->mkdir( $dir );
	}

	$sftp->put( $fileName, $fileName, NET_SFTP_LOCAL_FILE);
}

foreach( $iterate as $file )
	if( $file->isFile() ) {
		$fileName = str_replace( '\\', '/', $file );
		$hash = hash_file('md5', $fileName);

		if( !blacklist( $fileName )) {

			if( !isset( $hashes[$fileName] )) {
				echo "New file: $fileName\n";
				if( $mode == 'new' || $mode == 'all' ) upload($fileName);
			} elseif( $hashes[$fileName] != $hash ) {
				echo "File changed: $fileName\n";
				if( $mode == 'changed' || $mode == 'all' ) upload($fileName);
			}
		}
	}

